package com.wonder.email;

import com.wonder.admin.service.SysConfigService;
import com.wonder.admin.service.ParameterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

@Service
public class EmailSendService{

    @Autowired
    SysConfigService sysConfigService;

    @Autowired
    ParameterService parameterService;
    
    public String sendMessage(String email, String code){

        Properties prop = new Properties();
        prop.put("mail.smtp.auth",sysConfigService.getCacheKey("email_smtp_auth"));//true
        prop.put("mail.smtp.starttls.enable",sysConfigService.getCacheKey("email_smtp_auth_starttls_enable"));//true
        prop.put("mail.smtp.host",sysConfigService.getCacheKey("email_smtp_host"));//"smtp.gmail.com"
        prop.put("mail.smtp.port",sysConfigService.getCacheKey("email_smtp_port"));//"587"
        prop.put("mail.smtp.ssl.protocols", sysConfigService.getCacheKey("email_smtp_ssl_protocols"));//"TLSv1.2"

        String from = sysConfigService.getCacheKey("mail_username");//richmanhash.com@gmail.com
        String password = sysConfigService.getCacheKey("mail_password");//rvsalbklkzbgxdfk

        Session session = Session.getInstance(prop, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from,password);
            }
        });
        try{
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from,"THR"));
            msg.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
            msg.setSubject(parameterService.getKey("system.email.subject"));
            String content = parameterService.getKey("system.email.body");
            content = content.replace("{code}", code);
            msg.setContent(content,"text/html; charset=utf-8");
            Transport.send(msg);
            return "ok";
        } catch (AddressException | UnsupportedEncodingException ex){
//            Logger.getLogger(JavaUtils.class.getName()).log(Level.SEVERE,null,ex);
            ex.printStackTrace();
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
        return "fail";
    }
}
